<?php
class QuestionsController extends AppController {
    public $name = 'Questions';
    
    public function isAuthorized($user) {
        $this->loadModel('User');
        $this->User->id = $user['id'];
        $this->User->unbindModel(array('hasMany' => array('Test')));
        $role = $this->User->read('role');
        if($role['User']['role'] == 'none') {
            if(in_array($this->action, array('add', 'edit', 'delete', 'fmclear'))) {
                return true;
                $admin = false;
                $this->set('admin', $admin);
            }
        }
        if($role['User']['role'] == 'admin') {
            if(in_array($this->action, array('add', 'edit', 'delete', 'fmclear'))) {
                return true;
                $admin = true;
                $this->set('admin', $admin);
            }
        }
    }
    
    public function fmclear($testId, $questionId) {
        $this->set('title_for_layout', 'Sửa câu hỏi :: ChomoTech');
        $this->set('testId', $testId);
        $this->loadModel('Test');
        $this->Test->unbindModel(array('hasMany' => array('Question')));
        $this->Test->id = $testId;
        if(!$this->Test->exists()) {
            $this->Session->setFlash('Có lỗi xảy ra. Hãy thử lại sau.');
            $this->redirect(array('controller' => 'tests', 'action' => 'viewall'));
        }
        $test = $this->Test->read(array('user_id', 'question_updated'));
        if($test['Test']['user_id'] != $this->Auth->user('id') && $this->Session->read('Chomo.Current.Role') == 'none') {
            $this->Session->setFlash('Có lỗi xảy ra. Hãy thử lại sau.');
            $this->redirect(array('controller' => 'tests', 'action' => 'viewall'));
        }
        if($this->request->is('post')) {
            $this->Question->id = $questionId;
            $question = $this->Question->read();
            if($question['Question']['test_id'] != $testId) {
                $this->Session->setFlash('Có lỗi xảy ra. Hãy thử lại sau.');
                $this->redirect(array('controller' => 'tests', 'action' => 'view', $testId));
            }
            $question['Question']['content'] = strip_tags($question['Question']['content']);
            $i = 0;
            foreach($question['Answer'] as $answer) {
                $question['Answer'][$i]['content'] = strip_tags($answer['content']);
                $i++;
            }
            if($this->Question->save($question['Question'], false, array('content'))) {
                $this->loadModel('Answer');
                if($this->Answer->saveMany($question['Answer'], false)) {
                    $this->Session->setFlash('Lưu thành công.');
                    $this->redirect(array('controller' => 'tests', 'action' => 'edit', $testId));
                }
            }
        }
    }
    
    public function add($id, $step) {    
        $this->set('title_for_layout', 'Thêm câu hỏi :: ChomoTech');
        $this->set('test_id', $id);
        
        $this->loadModel('Test');
        $this->Test->id = $id;
        $this->Test->unbindModel(array('hasMany' => array('Question', 'Like')));
        $this->Test->unbindModel(array('belongsTo' => array('Subject', 'Grade', 'Training')));
        $test = $this->Test->read(array('user_id', 'question_updated', 'normal_updated'));
        if($test['Test']['user_id'] != $this->Auth->user('id') && $this->Session->read('Chomo.Current.Role') == 'none') {
             
            $this->redirect(array('controller' => 'tests', 'action' => 'viewall'));
        }
        
        switch($step) {
            case 'choise':
                $this->Session->delete('chomo.Question.Nums');
                $this->set('step', 'choise');
                if($this->request->is('post')) {
                     
                    if($this->request->data['Question']['choise'] == 'normal') {
                        $this->Session->write('question.Step', 'normal'); 
                        $this->redirect(array('controller' => 'questions', 'action' => 'add', $id, 'normal'));
                    } else if($this->request->data['Question']['choise'] == 'test') {
                        $this->Session->write('question.Step', 'test'); 
                        $this->redirect(array('controller' => 'questions', 'action' => 'add', $id, 'test1'));
                    }
                }
                break;
            case 'normal':
                $this->set('step', 'normal');
                if($this->request->is('post')) {
                     
                    $this->request->data['Question']['test_id'] = $id;
                    $this->request->data['Question']['type'] = 'normal';
                    $this->request->data['Question']['content'] = str_replace('<p>','',$this->request->data['Question']['content']);
                    $this->request->data['Question']['content'] = str_replace('</p>','<br />',$this->request->data['Question']['content']);
                    if($this->Question->save($this->request->data['Question'], true, array('content', 'type', 'test_id'))) {
                        $this->request->data['Test']['question_updated'] = (int)$test['Test']['question_updated'] + 1;
                        $this->request->data['Test']['normal_updated'] = (int)$test['Test']['normal_updated'] + 1;
                        if($this->Test->save($this->request->data['Test'], false, array('question_updated', 'normal_updated'))) {
                            $this->Session->setFlash('Lưu thành công.');
                            if($this->request->data['Question']['saveNext'] == 'normal') {
                                 
                                $this->redirect(array('controller' => 'questions', 'action' => 'add', $id, 'normal'));
                            } else {
                                 
                                $this->redirect(array('controller' => 'tests', 'action' => 'edit', $id));
                            }
                        }
                    }   
                }
                break;
            case 'test1':
                $this->Session->delete('chomo.Question.Nums');
                $this->set('step', 'test1');
                if($this->request->is('post')) {
                     
                    $this->Question->set($this->request->data);
                    if($this->Question->validates()) {
                        $this->Session->write('chomo.Question.Nums', $this->request->data['Question']['nums']);
                         
                        $this->redirect(array('controller' => 'questions', 'action' => 'add', $id, 'test2'));
                    }
                }
                break;
            case 'test2':
                if($this->Session->read('chomo.Question.Nums')) {
                    $this->set('step', 'test2');
                    $nums = $this->Session->read('chomo.Question.Nums');
                    $this->set('nums', $nums);
                    
                    if($this->request->is('post')) {
                         
                        /** Đ?m s? lư?ng đáp án đúng **/
                        $right = 0; $i = 1;
                        foreach($this->request->data['Answer'] as $answer) {
                            $this->request->data['Answer'][$i]['test_id'] = $id;
                            $i++;
                            if($answer['right'] == 1) {
                                $right++;
                            }
                        }
                        
                        if($right > 0) {
                            $this->request->data['Question']['test_id'] = $id;
                            $this->request->data['Question']['type'] = 'test';
                            /** C?p nh?t thông tin s? lư?ng câu h?i c?a đ? **/
                            $this->request->data['Test']['question_updated'] = (int)$test['Test']['question_updated'] + 1;
                            
                            $label = array('A','B','C','D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');
                            $i = 1;
                            foreach($this->request->data['Answer'] as $answer) {
                                $this->request->data['Answer'][$i]['label'] = $label[$i - 1];
                                $this->request->data['Answer'][$i]['content'] = str_replace('<p>','',$this->request->data['Answer'][$i]['content']);
                                $this->request->data['Answer'][$i]['content'] = str_replace('</p>','<br />',$this->request->data['Answer'][$i]['content']);
                                $i++;
                            }
                            $this->request->data['Question']['content'] = str_replace('<p>','',$this->request->data['Question']['content']);
                            $this->request->data['Question']['content'] = str_replace('</p>','<br />',$this->request->data['Question']['content']);
                            if($this->Question->saveAll($this->request->data)){
                                /** C?p nh?t thông tin s? lư?ng câu h?i c?a đ? **/
                                if($this->Test->save($this->request->data['Test'], true, array('question_updated'))) {
                                    $this->Session->setFlash('Lưu thành công.');
                                    if($this->request->data['Question']['saveNext'] == 'test') {
                                        $this->redirect(array('controller' => 'questions', 'action' => 'add', $id, 'test1'));
                                    } else { 
                                        $this->redirect(array('controller' => 'tests', 'action' => 'edit', $id));
                                    }
                                }
                            }
                        } else {
                            $this->Session->setFlash('Phải có ít nhất 1 đáp án đúng.');
                        }
                    }
                } else {
                     
                    $this->redirect(array('controller' => 'questions', 'action' => 'add', $id, 'test1'));
                }
                break;
            default:
                $this->redirect(array('controller' => 'questions', 'action' => 'add', $id, 'choise'));
                break;
        }
    }
    
    /** Xóa câu hỏi có mã là $questionId thuộc đề có mã là $testId **/
    public function delete($testId, $questionId) {
        $this->set('title_for_layout', 'Xóa câu hỏi :: ChomoTech');
        $this->loadModel('Test');
        $this->Test->id = $testId;
        
        /** Nếu mã đề $testId tồn tại **/
        if($this->Test->exists()) {
            $this->Test->unbindModel(array('hasMany' => array('Question')));
            $test = $this->Test->read(array('user_id', 'question_updated', 'normal_updated'));
            
            /** Nếu mã đề $testId là của người dùng hiện hành **/
            if($test['Test']['user_id'] == $this->Auth->user('id') || $this->Session->read('Chomo.Current.Role') == 'admin') {
                $this->Question->id = $questionId;
                $this->Question->unbindModel(array('hasMany' => array('Answer')));
                $question = $this->Question->read(array('test_id', 'type'));
                if($question['Question']['type'] == 'normal') {
                    $test['Test']['normal_updated'] = (int)$test['Test']['normal_updated'] - 1;
                }
                
                /** Nếu mã câu hỏi cần xóa $questionId đúng thuộc mã đề $testId **/
                if($question['Question']['test_id'] == $testId) {
                    $this->Question->bindModel(array('hasMany' => array('Answer')));
                    
                    /** Nếu người dùng xác nhận là xóa **/
                    if($this->request->is('post')) {
                         
                        if($this->Question->delete()) {
                            /** Cập nhật thông tin số lượng câu hỏi của đề **/
                            $test['Test']['question_updated'] = (int)$test['Test']['question_updated'] - 1;
                            if($this->Test->save($test, false, array('question_updated', 'normal_updated'))) {                        
                                $this->Session->setFlash('Xóa câu hỏi thành công.');
                                 
                                $this->redirect(array('controller' => 'tests', 'action' => 'edit', $testId));
                            } else {
                                $this->Session->setFlash('Có lỗi xảy ra. Hãy thử lại sau.');
                                 
                                $this->redirect(array('controller' => 'tests', 'action' => 'view', $testId));
                            }
                        } else {
                            $this->Session->setFlash('Có lỗi xảy ra. Hãy thử lại sau.');
                             
                            $this->redirect(array('controller' => 'tests', 'action' => 'view', $testId));
                        }
                    } else {
                        $this->set('testId', $testId);
                    }
                } else {
                    $this->Session->setFlash('Có lỗi xảy ra. Hãy thử lại sau.');
                     
                    $this->redirect(array('controller' => 'tests', 'action' => 'view', $testId));
                }
            } else {
                $this->Session->setFlash('Có lỗi xảy ra. Hãy thử lại sau.');
                 
                $this->redirect(array('controller' => 'tests', 'action' => 'view', $testId)); 
            }
        } else {
            $this->Session->setFlash('Có lỗi xảy ra. Hãy thử lại sau.');
             
            $this->redirect(array('controller' => 'tests', 'action' => 'viewall'));
        }
    }
    
    public function edit($testId, $questionId) {
        $this->set('title_for_layout', 'Sửa câu hỏi :: ChomoTech');
        $this->loadModel('Test');
        $this->Test->unbindModel(array('hasMany' => array('Question')));
        $this->Test->id = $testId;
        if(!$this->Test->exists()) {
            $this->Session->setFlash('Có lỗi xảy ra. Hãy thử lại sau.');
            $this->redirect(array('controller' => 'tests', 'action' => 'viewall'));
        }
        $test = $this->Test->read(array('user_id', 'question_updated'));
        if($test['Test']['user_id'] != $this->Auth->user('id') && $this->Session->read('Chomo.Current.Role') == 'none') {
            $this->Session->setFlash('Có lỗi xảy ra. Hãy thử lại sau.');
            $this->redirect(array('controller' => 'tests', 'action' => 'viewall'));
        }
        
        $this->Question->id = $questionId;
        $question = $this->Question->read();
        if($question['Question']['test_id'] != $testId) {
            $this->Session->setFlash('Có lỗi xảy ra. Hãy thử lại sau.');
             
            $this->redirect(array('controller' => 'tests', 'action' => 'view', $testId));
        }
        $this->set('questionView', $question);
        
        if($question['Question']['type'] == 'test') {
            if($this->request->is('post') && isset($this->request->data['Question'])) {
                 
                /** Đếm số đáp án đúng **/
                $right = 0;
                foreach($this->request->data['Answer'] as $answer) {
                    if($answer['right'] == 1) {
                        $right++;
                    }
                }
                if($right > 0) {
                    $this->request->data['Question']['test_id'] = $testId;
                    /** Thêm lại câu hỏi mới **/
                    $label = array('A','B','C','D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');
                    $i = 1;
                    foreach($this->request->data['Answer'] as $answer) {
                        $this->request->data['Answer'][$i]['label'] = $label[$i - 1];
                        $this->request->data['Answer'][$i]['question_id'] = $questionId;
                        $this->request->data['Answer'][$i]['content'] = str_replace('<p>','',$this->request->data['Answer'][$i]['content']);
                        $this->request->data['Answer'][$i]['content'] = str_replace('</p>','<br />',$this->request->data['Answer'][$i]['content']);
                        $i++;
                    }
                    $this->request->data['Question']['content'] = str_replace('<p>','',$this->request->data['Question']['content']);
                    $this->request->data['Question']['content'] = str_replace('</p>','<br />',$this->request->data['Question']['content']);
                    if($this->Question->save($this->request->data['Question'], true, array('content', 'test_id'))) {
                        $this->loadModel('Answer');
                        $this->Answer->unbindModel(array('belongsTo' => array('Question')));
                        $answer1 = $this->Answer->find('all', array('fields' => 'id', 'conditions' => array('question_id' => $questionId)));
                        if($this->Answer->saveMany($this->request->data['Answer'])) {
                            foreach($answer1 as $asw) {
                                $this->Answer->id = $asw['Answer']['id'];
                                $this->Answer->delete();
                            }
                            $this->Session->setFlash('Lưu thành công.');
                            $this->redirect(array('controller' => 'tests', 'action' => 'edit', $testId));
                        }
                    }
                } else {
                    $this->Session->setFlash('Cần có 1 đáp án đúng.');
                    $this->set('questionView', $question);
                }
            }
        } else {
            if($this->request->is('post') && isset($this->request->data['Question'])) {
                 
                $this->request->data['Question']['content'] = str_replace('<p>','',$this->request->data['Question']['content']);
                $this->request->data['Question']['content'] = str_replace('</p>','<br />',$this->request->data['Question']['content']);
                if($this->Question->save($this->request->data['Question'], true, array('content', 'test_id'))) {
                    $this->Session->setFlash('Lưu thành công.');
                     
                    $this->redirect(array('controller' => 'tests', 'action' => 'edit', $testId));
                }
            }
        }
    }
}
?>